package cn.larry.tools.weixin;

import cn.larry.tools.cons.Constants;
import cn.larry.tools.random.RandomPasswordTool;
import cn.larry.tools.string.StringTool;
import cn.larry.tools.time.TimeTool;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.URL;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;

/**
 * Larry
 * 2022/2/14 10:44
 * 服务商模式直联微信（V2版本接口）
 *
 * @Version 1.0
 */
public class WeixinISPPayTool {

    /**
     * 小程序支付预下单（预下单支付有效期：5分钟）
     *
     * @param appid
     * @param mch_id
     * @param sub_mch_id
     * @param amt
     * @param out_trade_no
     * @param notify_url
     * @param openid
     * @param spbill_create_ip
     * @param body
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static Map<String, String> JSAPIByApple(String appid,
                                                   String mch_id,
                                                   String sub_mch_id,
                                                   String amt,
                                                   String out_trade_no,
                                                   String notify_url,
                                                   String openid,
                                                   String spbill_create_ip,
                                                   String body,
                                                   String privateKey) throws Exception {

        Map<String, String> data = new HashMap<String, String>();
        data.put("body", body);
        data.put("out_trade_no", out_trade_no);
        data.put("fee_type", "CNY");
        data.put("total_fee", amt);// 订单金额
        data.put("appid", appid);
        data.put("mch_id", mch_id);
        data.put("sub_mch_id", sub_mch_id);
        data.put("spbill_create_ip", spbill_create_ip);
        data.put("notify_url", notify_url);
        data.put("trade_type", "JSAPI");  // 此处指定支付方式
        data.put("openid", openid);
        data.put("nonce_str", generateNonceStr());
        data.put("time_expire", TimeTool.getTimeDifference(Calendar.MINUTE, 5, Constants.COMMON_TIME_FORMAT_yyyyMMddHHmmss));// 交易结束时间

        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

        try {
            String reqXml = generateSignedXml(data, privateKey);
            String respStr = httpMethodPost(url, reqXml, "UTF-8", "10", "10");
//            log.info("统一下单应答：{}", respStr);
            Map<String, String> respMap = xmlToMap(respStr);
            String return_code = respMap.get("return_code");
            String result_code = respMap.get("result_code");
            if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)) {
                String prepay_id = respMap.get("prepay_id");

                if (StringTool.isNotBlank(prepay_id)) {
                    Map<String, String> jsapiData = new HashMap<String, String>();
                    jsapiData.put("timeStamp", System.currentTimeMillis() / 1000 + "");
                    jsapiData.put("nonceStr", RandomPasswordTool.randomGenerate2(18));
                    jsapiData.put("package", "prepay_id=" + prepay_id);
                    jsapiData.put("signType", "MD5");
                    jsapiData.put("appId", data.get("appid"));

                    jsapiData.put("paySign", generateSignature(jsapiData, privateKey, "MD5"));
                    return jsapiData;
                } else
                    throw new RuntimeException("小程序支付参数生成异常");
            } else
                throw new RuntimeException(respMap.get("return_msg"));
        } catch (Exception e) {
//            log.error("统一下单异常", e);
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 交易退款
     *
     * @param appid
     * @param mch_id
     * @param sub_mch_id
     * @param out_trade_no
     * @param transaction_id
     * @param total_fee
     * @param refund_fee
     * @param out_refund_no
     * @param wxPayConfig
     * @return
     * @throws Exception
     */
    public static Map<String, String> refund(String appid,
                                             String mch_id,
                                             String sub_mch_id,
                                             String out_trade_no,
                                             String transaction_id,
                                             String total_fee,
                                             String refund_fee,
                                             String out_refund_no,
                                             WXPayConfig wxPayConfig) throws Exception {

        Map<String, String> data = new HashMap<String, String>();
        data.put("total_fee", total_fee);// 订单金额
        data.put("refund_fee", refund_fee);// 申请退款金额
        data.put("out_refund_no", out_refund_no);// 商户退款单号（商户系统内部唯一）

        if (StringTool.isNotBlank(out_trade_no))
            data.put("out_trade_no", out_trade_no);// 商户订单号
        if (StringTool.isNotBlank(transaction_id))
            data.put("transaction_id", transaction_id);// 微信支付订单号（二选一，如果同时存在优先级：transaction_id> out_trade_no）

        data.put("nonce_str", generateNonceStr());
        data.put("appid", appid);
        data.put("mch_id", mch_id);
        data.put("sub_mch_id", sub_mch_id);

        try {
            Map<String, String> respMap = new WXPay(wxPayConfig).refund(data);
//            log.info("退款应答：{}", respMap.toString());
//            String return_code = respMap.get("return_code");
//            String result_code = respMap.get("result_code");
//            if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)) {
//            }
            return respMap;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 交易查询（不适合退款结果查询）
     *
     * @param appid
     * @param mch_id
     * @param sub_mch_id
     * @param out_trade_no
     * @param transaction_id
     * @param wxPayConfig
     * @return
     * @throws Exception
     */
    public static Map<String, String> orderquery(String appid,
                                                 String mch_id,
                                                 String sub_mch_id,
                                                 String out_trade_no,
                                                 String transaction_id,
                                                 WXPayConfig wxPayConfig) throws Exception {

        Map<String, String> data = new HashMap<String, String>();
        data.put("appid", appid);
        data.put("mch_id", mch_id);
        data.put("sub_mch_id", sub_mch_id);

        data.put("out_trade_no", out_trade_no);// 商户订单号
        data.put("transaction_id", transaction_id);// 微信支付订单号（二选一，如果同时存在优先级：transaction_id> out_trade_no）

        data.put("nonce_str", generateNonceStr());

        try {
            Map<String, String> respMap = new WXPay(wxPayConfig).orderQuery(data);
//            log.info("查询应答：{}", respMap.toString());
//            String return_code = respMap.get("return_code");
//            String result_code = respMap.get("result_code");
//            if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)) {
//            }
            return respMap;
        } catch (Exception e) {
            throw e;
        }
    }

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final Random RANDOM = new SecureRandom();

    /**
     * XML格式字符串转换为Map
     *
     * @param strXML XML字符串
     * @return XML数据转换后的Map
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilder documentBuilder = WXPayXmlUtil.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
//            log.warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
            throw ex;
        }

    }

    /**
     * 将Map转换为XML格式的字符串
     *
     * @param data Map类型数据
     * @return XML格式的字符串
     * @throws Exception
     */
    public static String mapToXml(Map<String, String> data) throws Exception {
        org.w3c.dom.Document document = WXPayXmlUtil.newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key : data.keySet()) {
            String value = data.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
        try {
            writer.close();
        } catch (Exception ex) {
        }
        return output;
    }


    /**
     * 生成带有 sign 的 XML 格式字符串
     *
     * @param data Map类型数据
     * @param key  API密钥
     * @return 含有sign字段的XML
     */
    public static String generateSignedXml(final Map<String, String> data, String key) throws Exception {
        return generateSignedXml(data, key, "MD5");
    }

    /**
     * 生成带有 sign 的 XML 格式字符串
     *
     * @param data     Map类型数据
     * @param key      API密钥
     * @param signType
     * @return 含有sign字段的XML
     */
    public static String generateSignedXml(final Map<String, String> data, String key, String signType) throws Exception {
        String sign = generateSignature(data, key, signType);
        data.put("sign", sign);
        return mapToXml(data);
    }


    /**
     * 判断签名是否正确
     *
     * @param xmlStr XML格式数据
     * @param key    API密钥
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
        Map<String, String> data = xmlToMap(xmlStr);
        if (!data.containsKey("sign")) {
            return false;
        }
        String sign = data.get("sign");
        return generateSignature(data, key).equals(sign);
    }

    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。使用MD5签名。
     *
     * @param data Map类型数据
     * @param key  API密钥
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
        return isSignatureValid(data, key, "MD5");
    }

    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。
     *
     * @param data     Map类型数据
     * @param key      API密钥
     * @param signType 签名方式
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(Map<String, String> data, String key, String signType) throws Exception {
        if (!data.containsKey("sign")) {
            return false;
        }
        String sign = data.get("sign");
        return generateSignature(data, key, signType).equals(sign);
    }

    /**
     * 生成签名
     *
     * @param data 待签名数据
     * @param key  API密钥
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key) throws Exception {
        return generateSignature(data, key, "MD5");
    }

    /**
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     *
     * @param data     待签名数据
     * @param key      API密钥
     * @param signType 签名方式
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key, String signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals("sign")) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        sb.append("key=").append(key);
        if ("MD5".equals(signType)) {
            return MD5(sb.toString()).toUpperCase();
        } else if ("HMAC-SHA256".equals(signType)) {
            return HMACSHA256(sb.toString(), key);
        } else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }


    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }


    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 生成 HMACSHA256
     *
     * @param data 待处理数据
     * @param key  密钥
     * @return 加密结果
     * @throws Exception
     */
    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 获取当前时间戳，单位秒
     *
     * @return
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 获取当前时间戳，单位毫秒
     *
     * @return
     */
    public static long getCurrentTimestampMs() {
        return System.currentTimeMillis();
    }

    /**
     * HTTP协议POST请求方法
     *
     * @throws Exception
     */
    public static String httpMethodPost(String url, String params, String gb, String readTime, String connectTime)
            throws Exception {
        if (null == gb || "".equals(gb)) {
            gb = "UTF-8";
        }
        StringBuffer sb = new StringBuffer();
        URL urls;
        HttpsURLConnection uc = null;
        BufferedReader in = null;
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new MyTrustManager()}, new SecureRandom());
            urls = new URL(url);
            uc = (HttpsURLConnection) urls.openConnection();
            uc.setSSLSocketFactory(sc.getSocketFactory());
            uc.setHostnameVerifier(new MyHostnameVerifier());
            uc.setRequestMethod("POST");
            uc.setDoOutput(true);
            uc.setDoInput(true);
            uc.setUseCaches(false);

            uc.setConnectTimeout(Integer.parseInt(connectTime) * 1000);
            uc.setReadTimeout(Integer.parseInt(readTime) * 1000);

            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            uc.connect();
            DataOutputStream out = new DataOutputStream(uc.getOutputStream());
            out.write(params.getBytes(gb));
            out.flush();
            out.close();
            in = new BufferedReader(new InputStreamReader(uc.getInputStream(), gb));
            String readLine = "";
            while ((readLine = in.readLine()) != null) {
                sb.append(readLine);
            }
            if (in != null) {
                in.close();
            }
            if (uc != null) {
                uc.disconnect();
            }
        } catch (Exception e) {
//			logger.error(null, e);
            throw e;
        } finally {
            if (uc != null) {
                uc.disconnect();
            }
        }
        return sb.toString();
    }

    private static class MyTrustManager implements X509TrustManager {
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class MyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

}
